<template>
  <div>
    <!-- 微信小程序：点击登录/注册：获取授权 -->
    <view class="g-button flexCenter" @click="login">
      <button
        type="primary"
        hover-class="none"
        @tap="getWeixinAuth"
        :disabled="infoAuthFlag"
      >
        授权微信登录
      </button>
    </view>
    <!-- 微信小程序：获取手机授权 -->
    <button
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumber"
      :disabled="phoneAuthFlag"
    >
      获取手机授权
    </button>
  </div>
</template>


<script>
export default {
  data() {
    return {
      code: "",
      infoAuthFlag: false, //  防止重复调起
      phoneAuthFlag: false, //  防止重复调起
    };
  },
  methods: {
    // 1、微信小程序：点击登录/注册：先获取code值
    login() {
      let that = this;
      uni.getProvider({
        service: "oauth",
        success: function (res) {
          if (~res.provider.indexOf("weixin")) {
            // 登录:获取code
            uni.login({
              provider: "weixin",
              success: (res2) => {
                that.code = res2.code;
              },
              fail: () => {
                uni.showToast({
                  title: "微信登录授权失败",
                  duration: 2000,
                });
              },
            });
          } else {
            // this.msg("请先安装微信或升级版本")
          }
        },
      });
    },
    // 2、微信小程序：点击登录/注册：获取授权
    getWeixinAuth() {
      this.infoAuthFlag = true;
      wx.getUserProfile({
        desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: async (info) => {
          // 这里用微信返回的数据去请求后台接口
          const loginGetToken = await this.$http(
            this.$API.mine.login.weixinLogin,
            {
              code: this.code,
              encryptedData: info.encryptedData,
              iv: info.iv,
            }
          );

          if (loginGetToken.data.success) {
            //  获取授权成功：后台自动登录，返回的token存储本地
            uni.setStorageSync("Token", loginGetToken.data.result.token);
            uni.showToast({
              title: "登录成功",
            });
            // 登录成功跳转页面
            uni.switchTab({ url: "/pages/home/index" });
          } else {
            this.infoAuthFlag = false;
          }
        },
        fail: (err) => {
          this.infoAuthFlag = false;
          uni.showToast({
            title: "微信登录授权失败",
            duration: 2000,
          });
        },
      });
    },
    // 3、微信小程序：获取手机授权(先获取用户信息授权)
    async getPhoneNumber(e) {
      this.phoneAuthFlag = true;
      if (e.detail.errMsg == "getPhoneNumber:ok") {
        const encryptedPhoneData = e.detail.encryptedData;
        const ivPhone = e.detail.iv;
        const trueToken = await this.$http(this.$API.mine.login.phone, {
          encryptedPhoneData,
          ivPhone,
        });
        // 登录成功：跳到我的首页
        if (trueToken.data.success) {
          uni.setStorageSync("Token", trueToken.data.result.token);
          uni.showToast({
            title: "登录成功",
          });
          uni.switchTab({ url: "/pages/home/index" });
        } else {
          this.phoneAuthFlag = false;
        }
        // uni.switchTab({
        //     url: '/pages/mine/index'
        // });
      } else {
        this.phoneAuthFlag = false;
        this.mes("登录失败");
      }
    },
    // 微信小程序：直接获取手机授权
    getPhoneNumber(e) {
      // 手机授权
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        const encryptedData = e.detail.encryptedData;
        const iv = e.detail.iv;
        uni.login({
          provider: "weixin",
          success: (loginRes) => {
            this.$http(this.$API.login.getSessionKey, {
              // microId:是appId;jsCode：是login接口返回的code
              microId: wx.getAccountInfoSync().miniProgram.appId,
              jsCode: loginRes.code,
            }).then((res) => {
              if (res.data.status == "success") {
                //  后台根据前台的参数返回sessionKey作为登录的参数
                const sessionKey = res.data.data;
                this.$http(this.$API.login.getNumber, {
                  encryptedData,
                  iv,
                  sessionKey,
                }).then((trueToken) => {
                  // 登录成功
                  if (trueToken.data.status == "success") {
                    const token = trueToken.data.data;
                    uni.setStorageSync("Token", token);
                    uni.showToast({
                      title: "登录成功",
                    });
                    this.getUserInfo();
                  } else {
                  }
                });
              }
            });
          },
          fail: (err) => {
            console.log("uni.login获取code失败：" + err.errMsg);
          },
        });
      } else {
        uni.showToast({
          title: "手机号授权失败",
          icon: "error",
          duration: 2000,
        });
      }
    },
  },
  created() {},
};
</script>


<style lang='scss' scoped>
</style>

